<template>
  <a-upload
    :show-upload-list="false"
    :before-upload="beforeUpload"
    :headers="headers"
    name="file"
    list-type="picture-card"
    class="avatar-uploader"
    action="/retailadmin/common/uploadImg"
    @change="handleChange"
  >
    <img v-if="imageSrc" :src="imageSrc.ali_url" />
    <div v-else>
      <a-icon :type="loading ? 'loading' : 'plus'" />
    </div>
  </a-upload>
</template>
<script>
import { getStore } from '@/utils/storage'

export default {
  props: {
    // 图片地址
    imageSrc: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      headers: {
        token: getStore('token')
      },
      loading: false
    }
  },
  // created() {
  //   // eslint-disable-next-line no-console
  //   console.log(1111, this.imageSrc)
  // },
  methods: {
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        const res = info.file.response
        if (res.code === 1) {
          // eslint-disable-next-line no-console
          console.log(222, res.data)
          // this.imageUrl = res.data.url
          this.$emit('update:imageSrc', res.data)
          this.loading = false
        }
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('图片类型必须是jpg或png格式!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('图片必须小于2M!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
